package receiver;

import service.StudentService;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.widget.Toast;
//Receive network change global broadcast from system
public class NetworkChangeReceiver extends BroadcastReceiver {
	@Override	
	public void onReceive(Context context, Intent intent) {
		//Check network is turning on or off
		if(isNetworkAvailable(context)){
			//ON: update
		    Intent service = new Intent(context, StudentService.class);
		    context.startService(service);
			Toast.makeText(context, "network turning ON, turn restart service", Toast.LENGTH_SHORT).show();
		} else{
			Toast.makeText(context, "network turning OFF", Toast.LENGTH_SHORT).show();
		}
	}
	public boolean isNetworkAvailable(Context context) {
	   ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
 	   if (connectivity == null) {
 	   } else {
 	      NetworkInfo[] info = connectivity.getAllNetworkInfo();
 	      if (info != null) {
 	         for (int i = 0; i < info.length; i++) {
 	            if (info[i].getState() == NetworkInfo.State.CONNECTED)
 	            	return true;
 	         }
 	      }
 	   }
 	   return false;
	}
}
